package com.topvision.controller.hes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.topvision.controller.AbstractController;
import com.topvision.init.InitProperties;
import com.topvision.model.hes.HesExpert;
import com.topvision.model.hes.HesUser;
import com.topvision.model.shrio.SysUser;
import com.topvision.service.hes.HesExpertService;
import com.topvision.service.hes.HesUserService;
import com.topvision.service.shrio.SysUserService;
import com.topvision.util.*;
import com.topvision.vo.hes.HesUserVO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 *
 * @author shengwm
 * @email 179653076@qq.com
 * @date 2017-08-28 11:23:20
 */
@RestController
@RequestMapping("hes/hesuser")
public class HesUserController extends AbstractController {
    @Autowired
    private HesUserService hesUserService;
    @Autowired
    private HesExpertService hesExpertService;
    @Autowired
    private InitProperties initProperties;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("hes/hesuser:list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<HesUserVO> hesUserList = hesUserService.queryList(query);
        int total = hesUserService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(hesUserList, total, query.getLimit(), query.getPage());

        return R.success().put("page", pageUtil);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{userId}")
    @RequiresPermissions("hes/hesuser:info")
    public R info(@PathVariable("userId") Long userId) {
        HesUser hesUser = hesUserService.queryObject(userId);
        return R.success().put("hesUser", hesUser);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("hes/hesuser:save")
    public R save(@RequestBody HesUser hesUser) {
        hesUserService.save(hesUser);
        return R.success();
    }

    /**
     * 保存用户为专家
     */
    @RequestMapping("/addExpert")
    @RequiresPermissions("hes/hesuser:save")
    public R addExpert(@RequestBody HesExpert hesExpert) {

        Map<String, Object> mapExist = new HashMap<>();
        mapExist.put("username", hesExpert.getUsername());
        List<HesExpert> hesExpertExists = hesExpertService.queryByParam(mapExist);
        HesExpert hesExpertExist = null;
        if (hesExpertExists != null && hesExpertExists.size() > 0) {
            hesExpertExist = hesExpertExists.get(0);
        }
        if (hesExpertExist != null) {
            hesExpertService.update(hesExpert);
        } else {

            HashMap<String, Object> map = new HashMap<String, Object>();
            String mac = String.valueOf(System.currentTimeMillis());
            map.put("companyid", "101");
            map.put("deviceid", mac);//时间戳作为唯一mac
            map.put("devicetype", "301");
            map.put("devicevendorid", "3");


            StringBuffer sb = new StringBuffer();
            sb.append("companyid=").append("101").append("&deviceid=").append(map.get("deviceid")).append("&devicetype=301").append("&devicevendorid=3");
            sb = new StringBuffer(Md5Util.getMd5("MD5", 0, null, sb.toString()));
            sb.append("123456");
            String digest = Md5Util.getMd5("MD5", 0, null, sb.toString());
            map.put("digest", digest);
            String result = HttpClientUtil.getZwanPostResult(Const.ZWAN_URL + "zwgw/createdevice", map);
            JSONObject json = JSON.parseObject(result);
            hesExpert.setZwannumber(json.getString("zwannumber"));
            hesExpert.setZwanpassword(json.getString("password"));
            hesExpert.setMac(mac);


            hesExpertService.save(hesExpert);
        }


        return R.success();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("hes/hesuser:update")
    public R update(@RequestBody HesUser hesUser) {
        hesUserService.update(hesUser);
        return R.success();
    }

    /**
     * 修改
     */
    @RequestMapping("/sysadmin")
    @RequiresPermissions("hes/hesuser:save")
    public R sysadmin(@RequestBody HesUser hesUser) {
        SysUser sysUser = new SysUser();
        sysUser.setUsername(hesUser.getUsername());
        sysUser.setPassword("123456");
        sysUser.setCreateUserId(1L);
        sysUser.setMobile(hesUser.getMobile());
        sysUser.setEmail(hesUser.getEmail());
        List<Long> roleList = new ArrayList<>();
        roleList.add(1L);
        sysUser.setRoleIdList(roleList);
        sysUser.setStatus(1);
        sysUserService.save(sysUser);

        if (hesUser.getUsername() != null && hesUser.getEmail() != null) {

            // creates a simple e-mail object
            SimpleMailMessage email = new SimpleMailMessage();
            email.setSubject("远程协助通知邮件");
            email.setFrom("no-reply@topvision-cv.com");
            email.setTo(hesUser.getEmail());
            StringBuffer stringBuffer = new StringBuffer();

            if (hesUser.getUsername() != null) {
                stringBuffer.append(hesUser.getUsername()).append(",您好：").append("\n").append("您已被设置为远程协助管理系统的管理员，登录名为：").append(hesUser.getUsername()).append(",密码为：123456").append(",请前往：http://122.112.226.39:8084/admin 登录您的帐号！");
            }
            email.setText(stringBuffer.toString());
            // sends the e-mail
            mailSender.send(email);

        }


        return R.success();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("hes/hesuser:delete")
    public R delete(@RequestBody Long[] userIds) {
        hesUserService.deleteBatch(userIds);
        return R.success();
    }

    /**
     * 保存科渡同步用户
     */
    @RequestMapping("/batchsave")
    @RequiresPermissions("hes/hesuser:save")
    public R batchsave() {
        //  hesUserService.save(hesUser);
        Map<String, Object> map = new HashMap<>();
        String url = Const.HES_URL + "Handler/AInterface.ashx?Command=synchronizeUsers";
        String hesresult = HttpClientUtil.getGetResult(url, map);
        JSONObject json = JSON.parseObject(hesresult);
        JSONArray array = json.getJSONArray("users");
        List<Map<String, Object>> mapListJson = (List) array;
        hesUserService.truncateTable();
        try {
            Thread.sleep(2000);
            logger.info("清空成功......");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        hesUserService.batchInsert(mapListJson);
        logger.info("插入成功，共计：" + mapListJson.size());
        return R.success();
    }


}
